package com.hellobike.haxing.modules.shop.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.system.vo.LoginUser;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.shop.entity.Shop;
import com.hellobike.haxing.modules.shop.service.IShopService;
import com.hellobike.haxing.modules.system.entity.SysUser;
import com.hellobike.haxing.modules.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 自提点
 * @Author: haxing-boot
 * @Date: 2020-02-03
 * @Version: V1.0
 */
@RestController
@RequestMapping("/product/extension")
@Slf4j
public class ExtensionController extends BaseController<Shop, IShopService> {
    @Autowired
    private IShopService shopService;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 分页列表查询
     *
     * @param shop
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "t_shop-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(Shop shop,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<Shop> queryWrapper = QueryGenerator.initQueryWrapper(shop, req.getParameterMap());
        queryWrapper.in("shop_type", 2, 3);
        Page<Shop> page = new Page<Shop>(pageNo, pageSize);
        IPage<Shop> pageList = shopService.page(page, queryWrapper.orderByDesc("id"));
        if (!CollectionUtils.isEmpty(pageList.getRecords())) {
            List<Long> sysUserIdList = pageList.getRecords().stream().map(Shop::getLeadShopId).collect(Collectors.toList());
            List<Shop> shops = shopService.list(new QueryWrapper<Shop>().lambda().in(Shop::getId, sysUserIdList));
            Map<Long, String> sysUserMap = shops.stream().collect(Collectors.toMap(Shop::getId, v -> v.getRealName()));
            for (Shop record : pageList.getRecords()) {
                try {
                    record.setSysLeaderName(sysUserMap.get(record.getLeadShopId()));
                } catch (Exception ex) {

                }
            }
        }
        return Result.ok(pageList);
    }

    /**
     * 开启店铺
     */
    @AutoLog(value = "开启店铺", operateType = 11)
    @RequestMapping(value = "/open")
    public Result<?> open(@RequestParam(name = "id", required = true) Long id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return shopService.openShop(id, sysUser.getUsername());
    }


    /**
     * 开启店铺
     */
    @AutoLog(value = "店铺详情", operateType = 11)
    @RequestMapping(value = "/detail")
    public Result<?> detail(@RequestParam(name = "id", required = true) Long id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Shop shop = shopService.getById(id);
        if (shop != null) {
            return Result.ok(shop);
        } else {
            return Result.error("店铺不存在");
        }
    }

    /**
     * 开启店铺
     */
    @AutoLog(value = "关闭店铺", operateType = 11)
    @RequestMapping(value = "/close")
    public Result<?> close(@RequestParam(name = "id", required = true) Long id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return shopService.closeShop(id, sysUser.getUsername());
    }


    @PostMapping(value = "/leader")
    @AutoLog(value = "查询系统用户信息", operateType = 12)
    public Result<?> leader(@RequestParam Long id) {
        List<Shop> shops = shopService.list(new QueryWrapper<Shop>()
                .lambda().eq(Shop::getShopType, 3).eq(Shop::getState, 1).ne(Shop::getId, id));
        List<JSONObject> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(shops)) {
            for (Shop shop : shops) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", shop.getId());
                jsonObject.put("text", shop.getRealName());
                list.add(jsonObject);
            }
        }
        return Result.ok(list);
    }

    @PostMapping(value = "/user-list")
    @AutoLog(value = "查询系统用户信息", operateType = 12)
    public Result<?> userList() {
        List<SysUser> sysUserList = sysUserMapper.selectList(new QueryWrapper<SysUser>()
                .lambda().eq(SysUser::getDeleted, 0));
        List<JSONObject> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(sysUserList)) {
            for (SysUser sysUser : sysUserList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", sysUser.getId());
                jsonObject.put("text", sysUser.getRealname());
                list.add(jsonObject);
            }
        }
        return Result.ok(list);
    }

    /**
     * 添加
     *
     * @param shop
     * @return
     */
    @AutoLog(value = "t_shop-添加", operateType = 2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody Shop shop) {

        return shopService.saveExtension(shop);
    }

    /**
     * 编辑
     *
     * @param shop
     * @return
     */
    @AutoLog(value = "t_shop-编辑", operateType = 3)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody Shop shop) {
        shopService.updateById(shop);
        return Result.ok("编辑成功!");
    }


    /**
     * 已开通的省份
     *
     * @return
     */
    @GetMapping("/openedProvinces")
    public Result getOpenedProvinces() {
        return Result.ok(shopService.getOpenedProvinces());
    }

    /**
     * 省下已开通的城市
     *
     * @param provinceId
     * @return
     */
    @GetMapping("/openedCitiesInProvince")
    public Result getOpenedCitiesByProvinceId(@RequestParam(name = "provinceId", required = true) Long provinceId) {
        return Result.ok(shopService.getOpenedCitiesByProvinceId(provinceId));
    }

    /**
     * 多个省下已开通的城市
     *
     * @param provinceIds
     * @return
     */
    @GetMapping("/openedCitiesInProvinces")
    public Result getOpenedCitiesByProvinceIds(@RequestParam(name = "provinceIds", required = true) String provinceIds) {
        return Result.ok(shopService.getOpenedCitiesByProvinceIds(Arrays.asList(provinceIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList())));
    }

    /**
     * 所有已开通的城市
     *
     * @return
     */
    @GetMapping("/allOpenedCities")
    public Result getAllOpenedCities() {
        return Result.ok(shopService.getAllOpenedCities());
    }

    /**
     * 城市下已开通的区县
     *
     * @param cityId
     * @return
     */
    @GetMapping("/openedDistrictsInCity")
    public Result getOpenedDistrictsByCityId(@RequestParam(name = "cityId", required = true) Long cityId) {
        return Result.ok(shopService.getOpenedDistrictsByCityId(cityId));
    }

    /**
     * 多个城市下已开通的区县
     *
     * @param cityIds
     * @return
     */
    @GetMapping("/openedDistrictsInCities")
    public Result getOpenedDistrictsByCityIds(@RequestParam(name = "cityIds", required = true) String cityIds) {
        return Result.ok(shopService.getOpenedDistrictsByCityIds(Arrays.asList(cityIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList())));
    }

    /**
     * 区县下已开通的街道
     *
     * @param districtId
     * @return
     */
    @GetMapping("/openedStreetsInDistrict")
    public Result getOpenedStreetsByDistrictId(@RequestParam(name = "districtId", required = true) Long districtId) {
        return Result.ok(shopService.getOpenedStreetsByDistrictId(districtId));
    }

    /**
     * 多个区县下已开通的街道
     *
     * @param districtIds
     * @return
     */
    @GetMapping("/openedStreetsInDistricts")
    public Result getOpenedStreetsByDistrictIds(@RequestParam(name = "districtIds", required = true) String districtIds) {
        return Result.ok(shopService.getOpenedStreetsByDistrictIds(Arrays.asList(districtIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList())));
    }

    /**
     * 街道下的自提点
     *
     * @param streetId
     * @return
     */
    @GetMapping("/shopsInStreet")
    public Result getShopsByStreetId(@RequestParam(name = "streetId", required = true) Long streetId) {
        return Result.ok(shopService.getShopsByStreetId(streetId));
    }

    /**
     * 多个街道下的自提点
     *
     * @param streetIds
     * @return
     */
    @GetMapping("/shopsInStreets")
    public Result getShopsByStreetIds(@RequestParam(name = "streetIds", required = true) String streetIds) {
        return Result.ok(shopService.getShopsByStreetIds(Arrays.asList(streetIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList())));
    }

    /**
     * 批量查询自提点
     *
     * @param shopIds
     * @return
     */
    @GetMapping("/getShopsByIds")
    public Result getShopsByIds(@RequestParam(name = "shopIds", required = true) String shopIds) {
        return Result.ok(shopService.listByIds(Arrays.asList(shopIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList())));
    }
}
